package com.bone.eventsweb.utils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.bone.eventsweb.dao.UserDao;
import com.bone.eventsweb.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtils {

    @Autowired
    private static UserDao staticUserDao;

    @Resource
    UserDao userDao;


    @PostMapping
    public void setUserService() {
         staticUserDao =  userDao;
    }


    /**
     *  生成token
     * @param userId
     * @param sign
     * @return
     */
    public static String createToken(String userId,String sign) {
        return JWT.create().withAudience(userId)  //将userId 保存到 token 里面，作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2)) //2小时后token过期
                .sign(Algorithm.HMAC256(sign)); //以 password 作为 token的密钥
    }


    /**
     *  获取当前登录用户信息
     * @return
     */
    public static UserEntity getCurrentUser(){

        try {
            HttpServletRequest request =
                    ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserDao.selectById(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }



}
